import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import User from '@/views/layout/user'
import Cart from '@/views/layout/cart'
import store from '@/store'
const Login = () => import('@/views/login')
const Myorder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const Prodetail = () => import('@/views/prodetail')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/searchList.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      // 二级路由
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },
    // 动态路由传参
    { path: '/prodetail/:id', component: Prodetail },
    { path: '/pay', component: Pay },
    { path: '/myorder', component: Myorder },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList }
  ]
})
// 全局路由前置导航守卫
// 所有的路由在被真正访问前都会先经过全局前置守卫
// 只有全局前置守卫放行后，才会到达对应的页面

// to：到哪里去，包含了要去哪的完整路由信息对象
// from：从哪来，包含了从哪来的完整路由信息对象
// next() :是否放行
//    next() : 放行
//    next(路径): 进行拦截，拦截到指定的路径去

// 定义一个数组存放需要权限访问的页面
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 如果访问需要权限的页面，用户token不存在则导航到login，否则放行
  if (authUrls.includes(to.path) && !store.getters.token) {
    next('/login')
  } else {
    next()
  }
})

export default router
